package com.xuebank.nfe.nfecar.beas.titlebar

import android.content.Context
import android.graphics.Color
import android.support.annotation.ColorInt
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.*
import android.widget.*
import com.wzn.libaray.R
import com.wzn.libaray.utils.CommonUtils
import com.wzn.libaray.utils.CommonUtils.dp2px
import com.wzn.libaray.utils.StatusBarUtil
import com.wzn.libaray.utils.ViewUtil
import com.wzn.libaray.utils.image.ImageUtils
import com.zhongtengxin.zhanzhao.beas.titlebar.MenuItem

import kotlin.collections.HashMap


/**
 * Created by luona on 17/7/27.
 */
class NewTitleBar : ConstraintLayout {

    private val TAG = NewTitleBar::class.java.simpleName

    private var mStatusBarView: View? = null
    private var mTitleView: RelativeLayout? = null
    //center
    var mCenterImageView: ImageView? = null
    var mCenterTextView: TextView? = null
    var addedtCenterRadioGroup: RadioGroup? = null
    //    var mRadioDatas: List<RadioData>? = null
    //menu
    var mLeftMenu: LinearLayout? = null
    var mRightMenu: LinearLayout? = null

    var isTitleBarAbove = false//是否遮盖页面内容

    //extra style
    var divideLine: View? = null

    private var mRightMenuItems: HashMap<Int, MenuItem>? = HashMap()
    private var mLeftMenuItems: HashMap<Int, MenuItem>? = HashMap()

    var mLeftMenuType = MenuItem.TYPE_TEXT
    var mRightMenuType = MenuItem.TYPE_TEXT
    var mLeftMenuHashCode = 0
    var mRightMenuHashCode = 0

    var titleColor = Color.WHITE
        private set

    private var mTitleTxtColor = Color.BLACK
    var mTitleTxtSize: Float = 20f
//            CommonUtils.dp2px(context, 32f).toFloat()

    constructor(context: Context) : super(context) {
        init(null, 0, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(attrs, 0, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(attrs, defStyleAttr, 0)
    }

    fun setTitleTxtColor(titleTxtColor: Int): NewTitleBar {
        this.mTitleTxtColor = titleTxtColor
        return this
    }

    fun setIsComputeStatusBarHeight(isComputeStatusBarHeight: Boolean): NewTitleBar {
        if (StatusBarUtil.isSupport()) {
            if (isComputeStatusBarHeight) {
                if (null == mStatusBarView) {
                    makeStatusbarView()
                    addView(mStatusBarView)
                }
            } else {
                if (null != mStatusBarView) {
                    removeView(mStatusBarView)
                    mStatusBarView = null
                }
            }
        }
        return this
    }

    private fun makeStatusbarView() {
        val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                StatusBarUtil.getStatusBarHeight(context))
        mStatusBarView = View(context)
        mStatusBarView?.layoutParams = layoutParams
    }

    private fun computeHeight(): Float {
        var suggestHeight = CommonUtils.dp2px(context, 48f).toFloat()
//        if (StatusBarUtil.isSupport()) {
//            suggestHeight += StatusBarUtil.getStatusBarHeight(context)
//        }
        return suggestHeight
    }

    private fun init(attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
        var dividerLineVisibility = View.VISIBLE
        var mSuggestHeight = computeHeight()
        if (null != attrs) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.TitleBar, defStyleAttr, defStyleRes)
            dividerLineVisibility = a.getInt(R.styleable.TitleBar_dividing_line_visibility, 0)
            mSuggestHeight = a.getDimension(R.styleable.TitleBar_EXACTLY_Height, mSuggestHeight)
            a.recycle()
        }
        setBackgroundColor(titleColor)
        isClickable = true
        if (id == -1)
            id = ViewUtil.generateViewId()

        if (StatusBarUtil.isSupport()) {
            val padding = StatusBarUtil.getStatusBarHeight(context)
            setPadding(0, 0, 0, 0)
        }

        //设置title的尺寸
        val rootLayoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mSuggestHeight.toInt())
        layoutParams = rootLayoutParams

        //初始化title栏按钮、标题所在layout
        mTitleView = RelativeLayout(context)
        mTitleView?.removeAllViews()
        val mTitleParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mSuggestHeight.toInt())
        mTitleParams.topToTop = if (mStatusBarView == null) LayoutParams.PARENT_ID else mStatusBarView?.id?:0
        mTitleParams.bottomToBottom = LayoutParams.PARENT_ID
        mTitleParams.leftToLeft = LayoutParams.PARENT_ID
        mTitleParams.rightToRight = LayoutParams.PARENT_ID
        addView(mTitleView, mTitleParams)

        //menu
        mLeftMenu = LinearLayout(context)
        mLeftMenu?.removeAllViews()
        mLeftMenu?.orientation = LinearLayout.HORIZONTAL
        mLeftMenu?.gravity = Gravity.BOTTOM
        val mLeftMenuParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mSuggestHeight.toInt())
        mLeftMenuParams.bottomToBottom = LayoutParams.PARENT_ID
        mLeftMenuParams.leftToLeft = LayoutParams.PARENT_ID
        addView(mLeftMenu, mLeftMenuParams)


        mRightMenu = LinearLayout(context)
        mRightMenu?.removeAllViews()
        mRightMenu?.orientation = LinearLayout.HORIZONTAL
        mRightMenu?.gravity = Gravity.BOTTOM
        val mRightMenuParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mSuggestHeight.toInt())
        mRightMenuParams.bottomToBottom = LayoutParams.PARENT_ID
        mRightMenuParams.rightToRight = LayoutParams.PARENT_ID
        addView(mRightMenu, mRightMenuParams)

        //初始化标题栏下方分割线
        divideLine = View(context)
        val layoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                dp2px(context, 0.5f))
        layoutParams.bottomToBottom = LayoutParams.PARENT_ID
        divideLine?.layoutParams = layoutParams
        divideLine?.setBackgroundColor(Color.parseColor("#dcdcdc"))
        divideLine?.visibility = if (0 == dividerLineVisibility) View.VISIBLE else if (1 == dividerLineVisibility) View.INVISIBLE else View.GONE
        addView(divideLine)
    }

    fun setTitleAbove(isTitleAbove: Boolean): NewTitleBar {
        isTitleBarAbove = isTitleBarAbove
        return this
    }

    fun setBackgroundByColor(@ColorInt color: Int): NewTitleBar {
        setBackgroundColor(color)
        titleColor = color
        return this
    }

    fun setLineViewVisibility(visibility: Int): NewTitleBar {
        divideLine?.visibility = visibility
        return this
    }

    private val imageViewWidthAndHeight: Int
        get() = computeHeight().toInt()

    fun setTitle(title: CharSequence): NewTitleBar {
        if (mCenterTextView == null) mCenterTextView = makeCenterTextView()
        mCenterTextView?.text = title.toString()
        if (mCenterTextView?.parent == null) {
            mTitleView?.removeAllViews()
            mTitleView?.addView(mCenterTextView)
        }
        return this
    }

    fun setTitle(titleId: Int): NewTitleBar {
        setTitle(context.getString(titleId))
        return this
    }

    private fun makeCenterTextView(): TextView {
        val textView = TextView(context)
        val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
        textView.layoutParams = layoutParams
        textView.textSize = mTitleTxtSize
        textView.setTextColor(mTitleTxtColor)
        textView.gravity = Gravity.CENTER
        return textView
    }

    /**
     * TODO 与textView保持一致
     */
    private fun makeCenterImageView(): ImageView {
        val imageButton = ImageView(context)
        val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        imageButton.layoutParams = layoutParams
        imageButton.scaleType = ImageView.ScaleType.CENTER_CROP
        return imageButton
    }

    fun setLeftMenuType(menuItemType: Int): NewTitleBar {
        this.mLeftMenuType = menuItemType
        return this
    }

    fun setRightMenuType(menuItemType: Int): NewTitleBar {
        this.mRightMenuType = menuItemType
        return this
    }

    fun addLeftMenuItem(menuItem: MenuItem?): NewTitleBar {
        if (menuItem == null)
            return this
        if (mLeftMenuItems?.get(menuItem.index) != null && mLeftMenuItems?.get(menuItem.index)?.hashCode() == menuItem.hashCode())
            return this
        mLeftMenuItems?.put(menuItem.index, menuItem)
        return this
    }

    fun isLeftMenuEmpty(): Boolean {
        if (mLeftMenuItems == null || mLeftMenuItems?.size?:0 <= 0) return true
        return false
    }

    fun addRightMenuItem(menuItem: MenuItem?): NewTitleBar {
        if (menuItem == null)
            return this
        if (mRightMenuItems?.get(menuItem.index) != null && mRightMenuItems?.get(menuItem.index)?.hashCode() == menuItem.hashCode())
            return this
        mRightMenuItems?.put(menuItem.index, menuItem)
        return this
    }

    fun showMenu(): NewTitleBar {
        val isShowLeftMenu = showMenu(mLeftMenuItems, mLeftMenuHashCode, mLeftMenu, mLeftMenuType)
        if (isShowLeftMenu) mLeftMenuHashCode = (mLeftMenuItems)!!.hashCode()

        val isShowRightMenu = showMenu(mRightMenuItems, mRightMenuHashCode, mRightMenu, mRightMenuType)
        if (isShowRightMenu) mRightMenuHashCode = (mRightMenuItems)!!.hashCode()

        return this
    }

    private fun showMenu(menuItems: HashMap<Int, MenuItem>?,
                         hashCode: Int,
                         menuParentView: LinearLayout?,
                         menuType: Int): Boolean {
        if (menuItems == null || menuItems.size <= 0 || hashCode == menuItems.hashCode())
            return false
        menuParentView?.removeAllViews()
        menuItems.keys
                .mapNotNull { menuItems[it] }
                .forEach {
                    if (menuType == MenuItem.TYPE_TEXT) {
                        val menuItemView = makeTxtMenuItem(it)
                        menuItemView.setOnClickListener(it.onClickListener)
                        if (menuItemView.parent == null) {
                            menuParentView?.addView(menuItemView)
                        }
                    } else if (menuType == MenuItem.TYPE_ICON) {
                        val menuItemView = makeImageMenuItem(it)
                        menuItemView.setOnClickListener(it.onClickListener)
                        if (menuItemView.parent == null) {
                            menuParentView?.addView(menuItemView)
                        }
                    }
                }
        return true
    }

    private fun makeTxtMenuItem(menuItem: MenuItem): TextView {
        val textView = TextView(context)
        var menuSize = CommonUtils.dp2px(context, 48f)
        var layoutParams = LinearLayout.LayoutParams(menuSize,
                menuSize)
        if (null != menuItem.menuWidth && null != menuItem.menuHeight) {
            var width = CommonUtils.dp2px(context, menuItem.menuWidth?:0f)
            var height = CommonUtils.dp2px(context, menuItem.menuHeight?:0f)
            layoutParams = LinearLayout.LayoutParams(width, height)
            layoutParams.rightMargin = 50
            layoutParams.bottomMargin = 20
        } else {
            val menuPading = CommonUtils.dp2px(context, 8f)
            textView.setPadding(menuPading, menuPading, menuPading, menuPading)
        }
        val menuTxtSize = menuItem.textSize

        textView.layoutParams = layoutParams


        textView.textSize = menuTxtSize.toFloat()
        textView.setTextColor(menuItem.textColor)
        if (null != menuItem.backgroundDrawable) {
            textView.background = menuItem.backgroundDrawable
        }
        val menuTxt = if (menuItem.titleResId != 0) context.getString(menuItem.titleResId?:0) else menuItem.title
        textView.text = menuTxt
        textView.gravity = Gravity.CENTER
        return textView
    }

    private fun makeImageMenuItem(menuItem: MenuItem): ImageView {
        val imageView = ImageView(context)
        val menuSize = CommonUtils.dp2px(context, 48f)
        val menuPading = CommonUtils.dp2px(context, 8f)
        val layoutParams = LinearLayout.LayoutParams(menuSize,
                menuSize)
        imageView.layoutParams = layoutParams
        imageView.setPadding(menuPading, menuPading, menuPading, menuPading)
        imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE
        if (menuItem.iconUrl != null && (menuItem.iconUrl?:"").isNotEmpty()) {
            ImageUtils.showImage(context, menuItem.iconUrl, imageView)
        } else if (menuItem.iconResId != 0) {
            imageView.setImageResource(menuItem.iconResId?:0)
        } else if (menuItem.icon != null) {
            imageView.setImageDrawable(menuItem.icon)
        }
        return imageView
    }

    fun reset(): NewTitleBar {
        mTitleView?.removeAllViews()
        mLeftMenu?.removeAllViews()
        mRightMenu?.removeAllViews()
        return this
    }

    /**
     * 默认不需要调用，使用hide后，需要重新显示title才需要使用
     */
    fun show(): NewTitleBar {
        visibility = View.VISIBLE
        return this
    }

    fun hide(): NewTitleBar {
        visibility = View.GONE
        return this
    }

}
